import backtrader as bt
import talib

# talib分析支撑位
class TalibSupportStrategy(bt.Strategy):
    params = (("period", 20),)

    def __init__(self):
        self.close = self.datas[0].close
        self.high = self.datas[0].high
        self.low = self.datas[0].low
        self.support_level = None

    def next(self):
        if len(self.close) > self.params.period:
            upper_band, middle_band, lower_band = talib.BBANDS(
                self.close, timeperiod=self.params.period
            )
            lowest_low = min(self.low.get(size=self.params.period))
            # 这里简单假设支撑位为布林带下轨减去近期最低价与布林带下轨之差的一半
            self.support_level = lower_band[-1] - (lower_band[-1] - lowest_low) / 2

            if self.data.close[0] > self.support_level and not self.position:
                self.order = self.buy()
            elif self.data.close[0] < self.support_level and self.position:
                self.order = self.sell()

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    f"BUY EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            elif order.issell():
                self.log(
                    f"SELL EXECUTED, Price: {order.executed.price}, Cost: {order.executed.value}, Size: {order.executed.size}"
                )
            self.order = None

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Canceled/Margin/Rejected")

    def log(self, txt):
        dt = self.datas[0].datetime.date(0)
        print(f"{dt}, {txt}")


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(TalibSupportStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
